package com.AEWMS.Utlis;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * 提供邮件发送服务
 * @author 黎海珊
 */
public class MailSender {
    private static final String FromEmail = "337613978@qq.com";
    private static final String EmailPassword = "uitofvcejyswbhgj";
    private static final String EmailSMTPhost = "smtp.qq.com";

    public static void sendMail(String emailTitle,String toEmail , String content){
        Properties props = new Properties();

        //设置邮件Debug功能
        props.setProperty("smtp.debug", "true");

        //设置是否开启邮件认证功能
        props.setProperty("mail.smtp.auth", "true");

        //设置SMTP端口
        props.put("mail.smtp.port", 25);

        //设置邮件传输的协议
        props.setProperty("mail.transport.protocol", "smtp");

        //设置发送验证邮件的邮箱
        props.setProperty("mail.smtp.host", EmailSMTPhost);

        Session session = Session.getInstance(props);
        session.setDebug(true);

        Message msg = new MimeMessage(session);
        try {
            msg.setSubject(emailTitle);
            msg.setText(content);
            msg.setSentDate(new Date());
            msg.setFrom(new InternetAddress(FromEmail,"学业预警系统","UTF-8"));

            Transport transport = session.getTransport();
            transport.connect(EmailSMTPhost,FromEmail,EmailPassword);

            transport.sendMessage(msg, new Address[] {new InternetAddress(toEmail)});
            System.out.println("发送成功");
            transport.close();
        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
        }
    }
}
